#include<sys/socket.h>
#include<sys/types.h>
#include"proto.h"
#include"sendF.h"
#include"cmdFront.h"
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void* cmdFrontend(void* sockp)
{
	int sock = *((int*)sockp);
	TCB cmdBlock;
	printf("Hey!\n");
	if (sock == -1)
		return NULL;
	printf("Supe!\n");
	while(1)
	{
		printf("OK>\n");
		if(recv(sock, &cmdBlock, sizeof(TCB), 0)<=0)
		{
			printf("Connection reset\n");
			close(sock);
			return NULL;
		}

		//Oh, we need to care about those hacks!!
		cmdBlock.fileName[MAX_FILE_NAME_LEN-1] = '\0';

		printf("New request:%d @ %s\n", cmdBlock.cmd, cmdBlock.fileName);

		if (cmdBlock.cmd == 0)
		{
			int flen = getFileLen(cmdBlock.fileName);
			send(sock, &flen, sizeof(flen), 0);
		}
		else if(cmdBlock.cmd == 1)
		{
			FILE* fin = fopen(cmdBlock.fileName, "rb");
			if (fin <= 0)
			{
				printf("Error while open file:%s\n", cmdBlock.fileName);
				continue;
			}
			sendFileSeg(sock, fin, cmdBlock.offset, cmdBlock.dataLen);
		}
	}
}

void Listenner()
{
	int servSock = socket(PF_INET, SOCK_STREAM, 0);
	struct sockaddr_in addr;
	socklen_t addrlen = sizeof(addr);

	addr.sin_family=AF_INET;
	addr.sin_port = PORT;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(servSock,(struct sockaddr*)&addr, addrlen);
	listen(servSock, 32);

	while(1)
	{
		int tmp = accept(servSock, (struct sockaddr*)&addr, &addrlen);
		/*A detached thread is created here, cause we don't need any info about 
		 * exit status of thread
		 */
		pthread_attr_t threadAttr;
		pthread_attr_init(&threadAttr);
		pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);

		/*
		 * Should be careful here, tmp may be changed before copy to cmdFrontend
		 * !!YOU SHOULD ADD SOME MECHINESE TO AVIOD THIS!!!
		 */
		pthread_t tid;
		pthread_create(&tid, &threadAttr, cmdFrontend, &tmp);
		pthread_attr_destroy(&threadAttr);
	}
}
